'''
Description: 
version: 1.0.0
Author: peng2.zhang
Date: 2021-09-28 13:49:43
LastEditors: peng2.zhang
LastEditTime: 2021-11-24 15:52:32
'''
# coding: utf-8
"""WeixinManage
Usage:
  weixin send_message --content=<content>  [--msgtype=<msgtype> --key=<key>]
  weixin -h | --help
  weixin --version

Options:
  -h --help     帮助.
  -v --version     查看版本号.
  --key=<key>  key设置 [default: 2eaf10d4-8b4d-46ee-be2a-988f988840b0].
  --msgtype=<msgtype>  msgtype设置 [default: text].
"""

'''
Description: 提供微信群发送消息功能
version: 1.0.0
Author: peng2.zhang
Date: 2020-08-31 17:28:03
LastEditors: peng2.zhang
LastEditTime: 2020-10-10 11:37:58
'''
import json
import base64
import hashlib
import requests
from docopt import docopt
from collections import defaultdict

headers = {
    "Content-type": "application/json"
}

def send_message(content, token="2eaf10d4-8b4d-46ee-be2a-988f988840b0", msgtype="text", mentioned_mobile_list=[], debug=False):
    data = {}
    weixin_url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={token}"
    data["msgtype"] = msgtype
    data[msgtype] = {"content": content, "mentioned_mobile_list": mentioned_mobile_list}
    # data["safe"] = 0
    if debug:
        print(data)
    res = requests.post(weixin_url, headers=headers, data=json.dumps(data))
    print(res.text)
    return res

def send_message1(content, token="2eaf10d4-8b4d-46ee-be2a-988f988840b0", msgtype="text"):
    weixin_url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={token}"
    data["msgtype"] = msgtype
    data[msgtype] = content
    res = requests.post(weixin_url, headers=headers, data=json.dumps(data))
    print(res.text)
    return res


class WeiXin:
    def __init__(self, token):
        self.token = token

    def send_pic(self, image):
        with open(image, 'rb') as f:  # 转换图片成base64格式
            data = f.read()
            encodestr = base64.b64encode(data)
            image_data = str(encodestr, 'utf-8')

        with open(image, 'rb') as f:  # 图片的MD5值
            md = hashlib.md5()
            md.update(f.read())
            image_md5 = md.hexdigest()

        url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={self.token}"

        headers = {"Content-Type": "application/json"}
        data = {
            "msgtype": "image",
            "image": {
                "base64": image_data,
                "md5": image_md5
            }
        }
        result = requests.post(url, headers=headers, json=data)
        print(result)
        return result


if __name__ == '__main__':
    # arguments = docopt(__doc__, version="1.0.0")
    # send_message(arguments["--content"], key=arguments["--key"], msgtype=arguments["--msgtype"])
    # print(arguments)
    # https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=7e93d83d-c878-4736-bdbc-e33bb2ff679d
    token = "7e93d83d-c878-4736-bdbc-e33bb2ff679d"
    # pic_path = "123456.jpeg"
    weixin1 = WeiXin(token)
    # weixin1.send_pic(pic_path)
